package service

import (
	"context"
	"errors"
	"github.com/rongcloud/server-sdk-go/v3/sdk"
	"gorm.io/gorm"
	Mysql "selfService/Databases"
	"selfService/tool"
	"selfService/个人相关/models"
	"time"
)

type SelfServiceImp struct {
}

// 传入phone信息  注册用户
func (this *SelfServiceImp) CreateUser(c context.Context, lg *CreateUserByPhoneRequest) (lgr *CreateUserByPhoneResponse, err error) {
	// 判断电话是否存在
	user := models.UserInfo{}
	if err = Mysql.DB.Model(models.UserInfo{}).Where("telephone = ? ", lg.Phone).Find(&user).Error; err != nil {
		return nil, err
	}
	// 如果存在直接返回 错误
	if user.Id != "" {
		return &CreateUserByPhoneResponse{
			State:   "200",
			Message: "创建失败，手机号已存在",
		}, nil
	}

	var userInfo *models.UserInfo
	var userRongyun sdk.User
	err2 := Mysql.DB.Transaction(func(tx *gorm.DB) error {
		// 权限，学生表和个人表的id是相同的
		idNum := tool.GenerateID()

		// 权限表创建
		indi_authority := &models.Indi_authority{
			Id:               idNum,
			Is_normal:        "1",
			Is_certification: "0",
			Is_merchant:      "0",
		}
		indi_authority_db := Mysql.DB.Create(indi_authority)
		if indi_authority_db.Error != nil{
			return indi_authority_db.Error
		}
		if indi_authority_db.RowsAffected == 0{
			return errors.New("创建失败")
		}

		// 学生表创建
		stu_info := &models.Stu_info{
			Id:       idNum,
			Is_valid: "0",
		}

		stu_info_db := Mysql.DB.Create(stu_info)
		if stu_info_db.Error != nil{
			return stu_info_db.Error
		}
		if stu_info_db.RowsAffected == 0{
			return errors.New("创建失败")
		}

		// 创建基本信息
		userInfo = &models.UserInfo{
			Id:           idNum,
			Telephone:    lg.Phone,
			Password:     lg.Password,
			Stu_info_id:  stu_info.Id,
			Indi_auth_id: indi_authority.Id,
			Nick_name:    "路人甲",
			Headshot_url: "http://img3.downza.cn/download/202008/152201-5f33989911385.jpg",
			CreateTime:   time.Now(),
			UpdateTime:   time.Now(),
		}
		create := Mysql.DB.Create(userInfo)
		if create.Error != nil{
			return create.Error
		}
		if create.RowsAffected == 0{
			return errors.New("创建失败")
		}

		// 融云账户创建
		rc := tool.RongYunUtil()
		userRongyun, err = rc.UserRegister(userInfo.Id, userInfo.Nick_name, userInfo.Headshot_url)
		if err != nil {
			return err
		}
		return nil
	})

	if err2 != nil {
		return &CreateUserByPhoneResponse{
			State:        "500",
			Message:      "创建失败",
		}, err2
	}

	return &CreateUserByPhoneResponse{
		State:        "200",
		Message:      "创建成功",
		Id:           userInfo.Id,
		TokenRongyun: userRongyun.Token,
	}, nil

}

// 传入 phone 和 password
func (this *SelfServiceImp) GetLogin(c context.Context, lg *LogininRequest) (lgr *LoginResponse, err error) {
	// 根据phone 和password查询数据
	users := []models.UserInfo{}
	if err = Mysql.DB.Model(models.UserInfo{}).Where("telephone = ? AND password = ?", lg.Phone, lg.Password).Find(&users).Error; err != nil {
		return nil, err
	}
	if len(users) == 0 {
		return nil, err
	} else {
		// 查询个人权限
		Indi_auth := models.Indi_authority{}
		Mysql.DB.Where("id = ?", users[0].Indi_auth_id).First(&Indi_auth)
		// 查询学生权限
		stu_info := models.Stu_info{}
		Mysql.DB.Where("id = ?", users[0].Stu_info_id).First(&stu_info)

		lgr = &LoginResponse{}
		lgr.Password = users[0].Password
		lgr.Account = users[0].Account
		lgr.Age = users[0].Age
		lgr.CityId = users[0].City_id
		lgr.DistrictId = users[0].District_id
		lgr.ExperiencePoint = users[0].Experience_point
		lgr.Gender = users[0].Gender
		lgr.HeadshotUrl = users[0].Headshot_url
		lgr.Id = users[0].Id
		lgr.Idiograph = users[0].Idiograph
		lgr.IndiAuthId = users[0].Indi_auth_id
		lgr.NickName = users[0].Nick_name
		lgr.ProvinceId = users[0].Province_id
		lgr.QqOpenid = users[0].Qq_openid
		lgr.StuInfoId = users[0].Stu_info_id
		lgr.Telephone = users[0].Telephone
		lgr.WalletId = users[0].Wallet_id
		lgr.WxOpenid = users[0].Wx_openid
		lgr.StuInfoResponse = &StuInfoResponse{
			Id:         stu_info.Id,
			KeepField1: stu_info.Keep_field1,
			KeepField2: stu_info.Keep_field2,
			StuNum:     stu_info.Stu_num,
			Name:       stu_info.Name,
			StuImg:     stu_info.Stu_img,
			IsValid:    stu_info.Is_valid,
		}
		lgr.IndiAuthorityResponse = &IndiAuthorityResponse{
			Id:              Indi_auth.Id,
			KeepField1:      Indi_auth.Keep_field1,
			KeepField2:      Indi_auth.Keep_field2,
			IsNormal:        Indi_auth.Is_normal,
			UnnormalReason:  Indi_auth.Unnormal_reason,
			IsCertification: Indi_auth.Is_certification,
			IsMerchant:      Indi_auth.Is_merchant,
		}
		return lgr, nil
	}
}

//传入id 查询个人权限列表
func (this *SelfServiceImp) GetIndiAuthority(c context.Context, ir *IndiAuthorityRequest) (irp *IndiAuthorityResponse, err error) {
	indi := []models.Indi_authority{}
	if err = Mysql.DB.Model(models.Indi_authority{}).Where("id = ? ", ir.Id).Find(&indi).Error; err != nil {
		return nil, err
	}
	if len(indi) == 0 {
		return nil, err
	} else {
		irp = &IndiAuthorityResponse{}
		irp.Id = indi[0].Id
		irp.KeepField1 = indi[0].Keep_field1
		irp.KeepField2 = indi[0].Keep_field2
		irp.IsNormal = indi[0].Is_normal
		irp.UnnormalReason = indi[0].Unnormal_reason
		irp.IsCertification = indi[0].Is_certification
		irp.IsMerchant = indi[0].Is_merchant
		return irp, nil
	}
}

//传入id  查询学生信息
func (this *SelfServiceImp) GetStuInfo(c context.Context, ir *StuInfoRequest) (irp *StuInfoResponse, err error) {
	indi := []models.Stu_info{}
	if err = Mysql.DB.Model(models.Stu_info{}).Where("id = ? ", ir.Id).Find(&indi).Error; err != nil {
		return nil, err
	}
	if len(indi) == 0 {
		return nil, err
	} else {
		irp = &StuInfoResponse{}
		irp.Id = indi[0].Id
		irp.KeepField1 = indi[0].Keep_field1
		irp.KeepField2 = indi[0].Keep_field2
		irp.StuNum = indi[0].Stu_num
		irp.Name = indi[0].Name
		irp.StuImg = indi[0].Stu_img
		irp.IsValid = indi[0].Is_valid
		return irp, nil
	}
}

// 传入id 返回个人信息
func (this *SelfServiceImp) GetUserInfo(c context.Context, lg *GetUserInfoByidRequest) (lgr *LoginResponse, err error) {
	users := []models.UserInfo{}
	if err = Mysql.DB.Model(models.UserInfo{}).Where("id = ? ", lg.Id).Find(&users).Error; err != nil {
		return nil, err
	}
	if len(users) == 0 {
		return nil, err
	} else {
		// 查询个人权限
		Indi_auth := models.Indi_authority{}
		Mysql.DB.Where("id = ?", users[0].Indi_auth_id).First(&Indi_auth)
		// 查询学生权限
		stu_info := models.Stu_info{}
		Mysql.DB.Where("id = ?", users[0].Stu_info_id).First(&stu_info)

		lgr = &LoginResponse{}
		lgr.Password = users[0].Password
		lgr.Account = users[0].Account
		lgr.Age = users[0].Age
		lgr.CityId = users[0].City_id
		lgr.DistrictId = users[0].District_id
		lgr.ExperiencePoint = users[0].Experience_point
		lgr.Gender = users[0].Gender
		lgr.HeadshotUrl = users[0].Headshot_url
		lgr.Id = users[0].Id
		lgr.Idiograph = users[0].Idiograph
		lgr.IndiAuthId = users[0].Indi_auth_id
		lgr.NickName = users[0].Nick_name
		lgr.ProvinceId = users[0].Province_id
		lgr.QqOpenid = users[0].Qq_openid
		lgr.StuInfoId = users[0].Stu_info_id
		lgr.Telephone = users[0].Telephone
		lgr.WalletId = users[0].Wallet_id
		lgr.WxOpenid = users[0].Wx_openid
		lgr.StuInfoResponse = &StuInfoResponse{
			Id:         stu_info.Id,
			KeepField1: stu_info.Keep_field1,
			KeepField2: stu_info.Keep_field2,
			StuNum:     stu_info.Stu_num,
			Name:       stu_info.Name,
			StuImg:     stu_info.Stu_img,
			IsValid:    stu_info.Is_valid,
		}
		lgr.IndiAuthorityResponse = &IndiAuthorityResponse{
			Id:              Indi_auth.Id,
			KeepField1:      Indi_auth.Keep_field1,
			KeepField2:      Indi_auth.Keep_field2,
			IsNormal:        Indi_auth.Is_normal,
			UnnormalReason:  Indi_auth.Unnormal_reason,
			IsCertification: Indi_auth.Is_certification,
			IsMerchant:      Indi_auth.Is_merchant,
		}
		return lgr, nil
	}
}

// 修改用户资料
//rpc UpdateUserInfo(UpdateUserInfo_request) returns(UpdateUserInfo_response); // 修改用户资料
func (this *SelfServiceImp) UpdateUserInfo(c context.Context, lg *UpdateUserInfoRequest) (lgr *UpdateUserInfoResponse, err error) {
	user := &models.UserInfo{
		Nick_name:    lg.NickName,
		Gender:       lg.Gender,
		Idiograph:    lg.Idiograph,
		Telephone:    lg.Telephone,
		Age:          lg.Age,
		Headshot_url: lg.HeadshotUrl,
		Password:     lg.Password,
	}
	updates := Mysql.DB.Model(&user).Where("id = ?", lg.Id).Updates(user)
	lgr = &UpdateUserInfoResponse{}
	if updates.Error != nil {
		lgr.State = "500"
		lgr.Message = "内部错误"
		return lgr, err
	}

	lgr.State = "200"
	lgr.Message = "修改成功"
	return lgr, nil
}
